﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace ConsoleMarshal
{
    class Program
    {
        static void Main(string[] args)
        {
            var item=new SItem { x = 1, y = 2 };
            IntPtr intptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SItem)));
            Marshal.StructureToPtr(item, intptr,true);
            Marshal.FreeHGlobal(intptr);
            var newItem = new SItem();
            if (intptr == IntPtr.Zero) return;
            newItem = (SItem)Marshal.PtrToStructure(intptr,typeof(SItem));



            Console.WriteLine("\nStringToGlobalAnsi\n");

            // Create a managed string.
            String managedString = "I am a managed String";
            Console.WriteLine("1) managedString = " + managedString);

            // Marshal the managed string to unmanaged memory.
            IntPtr stringPointer = (IntPtr)Marshal.StringToHGlobalAnsi(managedString);
            Console.WriteLine("2) stringPointer = {0}", stringPointer);

            // Get the string back from unmanaged memory
            String RetrievedString = Marshal.PtrToStringAnsi(stringPointer);
            Console.WriteLine("3) Retrieved from unmanaged memory = " + RetrievedString);

            // Always free the unmanaged string.
            Marshal.FreeHGlobal(stringPointer);

            // IntPtr handle value is still the same:
            Console.WriteLine("4) stringPointer = " + stringPointer);

            // However, it contains no data after being freed:
            String RetrievedString2 = Marshal.PtrToStringAnsi(stringPointer);
            Console.WriteLine("5) RetrievedString2 = " + RetrievedString2);
            Console.ReadKey();
        }
    }

    struct SItem
    {
        public int x { get; set; }
        public int y { get; set; }

    }

    public struct SContext
    {
        public int numOfItems { get; set; }
        public IntPtr items { get; set; }
    }
}
